using AutoMapper;
using Core.SimpleTemp.Application;
using Core.SimpleTemp.Common.Authorization;
using Core.SimpleTemp.Common.PagingQuery;
using Core.SimpleTemp.Entitys;
using Core.SimpleTemp.Mvc.Api.Internal;
using Core.SimpleTemp.Repositories.Internal;
using Core.Toolkit.Authorization;
using Core.Toolkit.Core;
using Core.Toolkit.Core.Api;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Cors;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace Core.SimpleTemp.Mvc.Api.sys
{
    /// <summary>
    /// FL_SystemFileLevel
    ///</summary>
    [ApiExplorerSettings(GroupName = "Sys")]//swagger分类标签
    [Route("api/[controller]")]//路由说明
    [EnableCors("any")]//跨域规则
    [ApiController]//APi标识Controller
    public class FL_SystemFileLevelController : CoreApiController
    {
        private readonly CoreDBContext _coreDBContext;
        private readonly FL_SystemFileLevelService _service;
        /// <summary>
        /// FL_SystemFileLevel
        ///</summary>
        public FL_SystemFileLevelController(FL_SystemFileLevelService service, CoreDBContext coreDBContext)
        {
            _service = service;
            _coreDBContext = coreDBContext;
        }

        #region 基础增删改查
        /// <summary>
        /// 查询
        ///</summary>
        /// <param name="pagingQueryModel"></param>
        /// <returns></returns>

        [HttpPost("GetList")]
        [PermissionFilter(nameof(FL_SystemFileLevelController) + "_" + nameof(FL_SystemFileLevelController.GetList), AuthorizationConst.LIST)]
        public async Task<IActionResult>
            GetList(PagingModel<FL_SystemFileLevelDto>
                pagingQueryModel)
        {
            ////工厂
           //pagingQueryModel.Model.CreateFactory = UserIdentity.Factory;

            IPageModel<FL_SystemFileLevelDto>
                result = await _service.GetList(pagingQueryModel);

            //result.PageData.ForEach(dto =>
            //{
            //    var str = "";
            //    dto.FL_SystemFileLevelDept.ToList().ForEach(a =>
            //    {
            //        str += _coreDBContext.SysDepartment.Where(x => x.Id == a.DeptId).FirstOrDefault()?.Name + ",";
            //    });
            //    if (str.Length > 0)
            //        str = str.Substring(0, str.Length - 1);
            //    dto.Mark03 = str;

            //});
            return this.JsonSuccess(result);
        }

        /// <summary>
        /// 添加/修改
        ///</summary>
        /// <param name="dto"></param>
        /// <returns></returns>

        [HttpPost("Save")]
        [PermissionFilter(nameof(FL_SystemFileLevelController) + "_" + nameof(FL_SystemFileLevelController.SaveAsync), AuthorizationConst.SAVE)]
        public async Task<IActionResult>
            SaveAsync(FL_SystemFileLevelDto dto)
        {
            //添加
       //   if (Equals(dto.Id, Guid.Empty))
          if(dto.AddEdit =="Add")
            {
                dto.Id = Guid.Empty;
                dto.IsDeleted = false;
                dto.CreateUser = UserIdentity.Id;
                dto.CreateFactory = UserIdentity.Factory;
                dto.CreateTime = System.DateTime.Now;
                await _service.InsertAsync(dto);
                dto.Id = Guid.Empty;
                return this.JsonSuccess(string.Empty);
            }
            else 
            {
                dto.IsDeleted = false;
                dto.UpdateUser = UserIdentity.Id;
                dto.CreateFactory = UserIdentity.Factory;
                dto.UpdateTime = System.DateTime.Now;
                await _service.UpdateAsync(dto);
                dto.Id = Guid.Empty;
                return this.JsonSuccess(string.Empty);
            }
        }

        /// <summary>
        /// DeleteMuti
        ///</summary>
        /// <param name="ids"></param>
        /// <returns></returns>
        [HttpPost("DeleteMuti")]
        [PermissionFilter(nameof(FL_SystemFileLevelController) + "_" + nameof(FL_SystemFileLevelController.DeleteMutiAsync), AuthorizationConst.DELETE)]
        public async Task<IActionResult>
            DeleteMutiAsync([FromBody]Guid[] ids)
        {
            List<Guid> newList = new List<Guid>();
            for (int i = 0; i < ids.Count(); i++)
            {
                if(_coreDBContext.FL_SystemFileLevel.Where(x=>x.Id == ids[i]).Where(b=>b.IsDeleted==false).ToList().Count >0)
                {
                    newList.Add(ids[i]);
                }
            }
            await _service.DeleteBatchAsync(newList.ToArray());

            return this.JsonSuccess();
        }


        /// <summary>
        /// 根据ID获取信息
        ///</summary>
        /// <param name="id"></param>
        /// <returns></returns>

        [HttpGet("Get")]
        public async Task<IActionResult> Get(Guid id)
        {
            var model = await _service.GetAsync(id);
            if (model == null) return this.JsonFaild("未找到对应数据:" + id);
            var retObj = new
            {
               // model.Id,
               // model.MS_InstitutionName,//
               // model.MS_FileNo,
               //// FileLeveName = model.FL_FileLevel.FileLeve,
               // fileLeve= model.FileLeve,
               // model.MS_ImplementationDate,
               // model.MS_ReviewCycle,
               // model.MS_ReviewDate,
               // model.MS_RevisionTime,
               // model.MS_Mark,
               // model.Attachment,
               // model.AttachmentName,
               // model.FL_SystemFileLevelDept,

                //model.InvestigationContents,//
                //model.CreateFactory,//
                //model.CreateDept,//
                //model.UpdateDept,//
            };
           // model.FL_SystemFileLevelDept = retObj.FL_SystemFileLevelDept;
            return this.JsonSuccess(retObj);
        }


        /// <summary>
        /// 导出
        ///</summary>
        /// <param name="pagingQueryModel"></param>
        /// <returns></returns>

        [HttpPost("Export")]
        [PermissionFilter(nameof(FL_SystemFileLevelController) + "_" + nameof(FL_SystemFileLevelController.Export), AuthorizationConst.EXPORT)]
        public async Task<IActionResult>
            Export(PagingModel<FL_SystemFileLevelDto>
                pagingQueryModel)
        {
            var fileName = await _service.Export(pagingQueryModel);
            if (string.IsNullOrWhiteSpace(fileName))
                return this.JsonFaild(NULL_DATA_FOR_EXCEL_EXPORT);
            return this.JsonSuccess(fileName);
        }


        /// <summary>
        /// 导入
        /// </summary>
        /// <param name="data"></param>
        /// <param name="file"></param>
        /// <returns></returns>
        [HttpPost("Import")]
        //[PermissionFilter(nameof(FX_EquipmentFacilitiesController) + "_" + "导入")]
        public async Task<IActionResult> ImportAsync([FromForm]String data, [FromForm]List<IFormFile> file)
        {
            var retMeg = await _service.ImportAsync(file[0], data);
            if (!retMeg.Any())
            {
                return this.JsonSuccess();
            }
            else
            {
                return this.JsonFaild(retMeg[0].ToString());
            }
        }
        #endregion


    }
}
